package com.kcdown.train.util;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONObject;
import org.json.JSONArray;

public class GoogleSearcher
{

	public GoogleSearcher()
	{
		searchResults = new ArrayList<GoogleSearchResult>();
	}

	public void searchByLocation(String location,int page)
	{
		String generalUrl = "http://ajax.googleapis.com/ajax/services/search/local?v=1.0&rsz=large&mrt=localonly&q=";
		String urlString = generalUrl + URLEncoder.encode(location.replaceAll("\\s+", "%20")) + "+%E7%81%AB%E8%BD%A6%E7%A5%A8";
		search(urlString,page);
	}
	
	public void searchByGPS(String gps,int page)
	{
		String generalUrl = "http://ajax.googleapis.com/ajax/services/search/local?v=1.0&rsz=large&mrt=localonly&q=%E7%81%AB%E8%BD%A6%E7%A5%A8%E4%BB%A3%E5%94%AE%E7%82%B9&sspn=0.05%2C+0.1&llsep=500%2C+500&sll=";
		String urlString = generalUrl + URLEncoder.encode(gps);
		search(urlString,page);
	}
	
	public void search(String urlString,int page)
	{
		searchResults.clear();
		URL url = null;
		JSONArray jsonArr = null;
		try
		{
			url = new URL(urlString + "&start="+page);
			URLConnection conn = url.openConnection();
			conn.addRequestProperty("Referer","http://www.informatik.uni-trier.de/~ley/db/");

			StringBuilder builder = new StringBuilder();
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
			String line;
			while ((line = br.readLine()) != null)
			{
				builder.append(line);
			}
			br.close();
			jsonArr = new JSONObject(builder.toString()).getJSONObject("responseData").getJSONArray("results");
			parseResults(jsonArr);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		
	}

	/*
	 * public static void main(String[] args) { GoogleSearcher gs = new
	 * GoogleSearcher(16); gs.search("Paris Hilton"); GoogleSearchResult[] rs =
	 * gs.getSearchResults(); for (int i=0; i<rs.length; ++i) {
	 * System.out.println(rs[i].getUnescapedUrl()); } }
	 */

	private void parseResults(JSONArray jsonArr)
	{
		for (int i = 0; i < jsonArr.length(); ++i)
		{
			GoogleSearchResult result = new GoogleSearchResult();
			try
			{
				JSONObject jsonObj = jsonArr.getJSONObject(i);
				result.setTitle(jsonObj.getString("titleNoFormatting"));
				result.setTitleNoFormatting(jsonObj.getString("addressLines"));
				result.setAddress(jsonObj.getString("streetAddress"));
				//phoneNumbers
				String string = jsonObj.getString("phoneNumbers");
				JSONArray phones = new JSONArray(string);
				result.setPhoneNumber(phones.getJSONObject(0).getString("number")) ;
				searchResults.add(result);	
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}

	public ArrayList<GoogleSearchResult> getSearchResults()
	{
		return searchResults;
	}
	protected ArrayList<GoogleSearchResult> searchResults;
	
}